import { fourDotsSpinnerSvg } from '@/assets/svg/launch.ts'
import { ElLoading } from 'element-plus'

/**
 * 获取当前主题对应的Launch背景色
 * @returns 背景色字符串
 */
const getLaunchBackground = (): string => {
    const isDark = document.documentElement.classList.contains('dark')
    return isDark ? 'rgba(7, 7, 7, 0.85)' : '#fff'
}

const DEFAULT_LAUNCH_CONFIG = {
    lock: true,
    get background() {
        return getLaunchBackground()
    },
    svg: fourDotsSpinnerSvg,
    svgViewBox: '0 0 40 40',
    customClass: 'art-loading-fix'
} as const

interface LaunchInstance {
    close: () => void
}

let launchInstance: LaunchInstance | null = null

export const launchService = {
    /**
     * 显示 loading
     * @returns 关闭 loading 的函数
     */
    showLoading(): () => void {
        if (!launchInstance) {
            // 每次显示时获取最新的配置，确保背景色与当前主题同步
            const config = {
                ...DEFAULT_LAUNCH_CONFIG,
                background: getLaunchBackground()
            }
            launchInstance = ElLoading.service(config)
        }
        return () => this.hideLoading()
    },

    /**
     * 隐藏 loading
     */
    hideLoading(): void {
        if (launchInstance) {
            launchInstance.close()
            launchInstance = null
        }
    }
}
